﻿using System.Collections.ObjectModel;
using Gwn.Library.MvpVm.Base;
using Gwn.Library.MvpVm.Entities;
using Gwn.Library.MvpVm.Events;
using Gwn.Library.MvpVm.Extensions;
using Gwn.Library.MvpVm.ViewModels;
using Gwn.Module.UserManager.Interfaces;
using Gwn.Module.UserManager.Types;
using Microsoft.Practices.Unity;

namespace Gwn.Module.Security
{
    /// <summary>
    /// Resolved by the SecurityModule - PresenterBase does the wire-up 
    /// of View and ViewModel based on type registration in SecurityModule.
    /// </summary>
    public class SecurityPresenter : PresenterBase
    {
        private ObservableCollection<User> UserListExample { get; set; }

        /// <summary>
        /// Gets or sets the BLL.
        /// </summary>
        /// <value>The BLL.</value>
        [Dependency]
        public IBusinessLogicLayer Bll { get; set; }

        /// <summary>
        /// Gets the security view model.
        /// </summary>
        /// <value>The security view model.</value>
        public SecurityCommandViewModel SecurityViewModel
        {
            get { return (SecurityCommandViewModel)ViewModel; }
        }

        /// <summary>
        /// Called by application controller when view is activated
        /// </summary>
        public override void ViewActivated()
        {
            base.ViewActivated();

            // Refresh list 
            Bll.GetUserListAsync();
        }

        public override void Initialize()
        {
            // Logs initialize
            base.Initialize();

            // Subscribe to process events
            EventAggregator.GetEvent<ProcessEvent>().Subscribe(HandleProcessEvents);

            // Get the user list - handled by the HandleProcessEvents below
            Bll.GetUserListAsync();

        }

        /// <summary>
        /// Handles the process events.
        /// </summary>
        /// <param name="e">The <see cref="Gwn.Library.MvpVm.Events.ProcessEventArgs"/> instance containing the event data.</param>
        public void HandleProcessEvents(ProcessEventArgs e)
        {
            // Only handle if this presenter is active
            if (!IsActivePresenter) return;
            
            // Not expected but let us know if one occurs...
            if (e.IsError) throw e.Exception;

            // We'll only handle UserManagerProcessType.ListData
            var processType = e.ProcessType.GetProcessType<UserManagerProcessType>();
            if (processType== UserManagerProcessType.ListData)
            {
                if (e.IsError) return;
                UserListExample = e.GetData<ObservableCollection<User>>();

                SecurityViewModel.Message = "Hello World from Presenter! There are " + UserListExample.Count + " users loaded";
            }
            
        }

    }
}
